<template>
  <div style="width: 100%">
    <div class="dialogTitle" style="margin-bottom: 20px">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="1" disabled></el-tab-pane>
        <el-tab-pane label="扩展信息" name="2" disabled></el-tab-pane>
      </el-tabs>
    </div>
    <div style="width: 100%" v-if="visible">
      <el-form
        style="width: 99%"
        size="medium"
        ref="form"
        v-show="activeName === '1'"
        :model="formData"
        label-width="100px"
        :disabled="dialogType === 'view'"
        :rules="rules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="中文名称" prop="nameCn">
              <el-input
                placeholder="请输入"
                v-model="formData.nameCn"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接口类型" prop="type">
              <el-select style="width: 100%" v-model="formData.type">
                <el-option label="业务接口" :value="1"></el-option>
                <el-option label="功能接口" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-col :span="12">
          <el-form-item label="英文名称" prop="nameEn">
            <el-input placeholder="请输入" v-model="formData.nameEn"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="编码标识" prop="name">
            <el-input
              placeholder="请输入小写字母、下划线、数字"
              :disabled="dialogType !== 'add'"
              v-model="formData.name"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="接口数据类型" prop="refType">
            <el-select style="width: 100%" v-model="formData.refType">
              <el-option label="实体" :value="1"></el-option>
              <el-option label="关系" :value="2"></el-option>
              <el-option label="实体和关系" :value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="是否需要配置" prop="configFlag">
            <el-select style="width: 100%" v-model="formData.configFlag">
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="英文描述">
            <el-input
              v-model="formData.describeEn"
              show-word-limit
              maxlength="1000"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="中文描述" prop="describeCn">
            <el-input
              v-model="formData.describeCn"
              show-word-limit
              maxlength="1000"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-form>
      <el-collapse v-show="activeName === '2'" v-model="collapse">
        <el-collapse-item name="1" title="扩展属性">
          <avue-crud
            :option="{ ...option, selection: dialogType !== 'view' }"
            :table-loading="loading"
            :data="propertiesData"
            @selection-change="(v) => (propertiesSelection = v)"
            ref="crud"
          >
            <template slot="menuLeft">
              <el-button
                size="small"
                type="primary"
                :disabled="dialogType === 'view'"
                @click="
                  $refs['gpd'].open(propertiesData, { purpose: formData.type })
                "
              >
                添加
              </el-button>
              <el-button
                size="small"
                type="primary"
                :disabled="dialogType === 'view'"
                @click="$refs['ap'].open()"
              >
                新增并添加
              </el-button>
              <el-button
                size="small"
                type="danger"
                :disabled="
                  dialogType === 'view' || propertiesSelection.length === 0
                "
                @click="remove()"
              >
                移除
              </el-button>
            </template>

            <template slot="columnDefault" slot-scope="{ row }">
              <span :id="'cell--' + row.oid">{{
                setLabel(row, "cell--")
              }}</span>
            </template>
          </avue-crud>
        </el-collapse-item>
        <el-collapse-item
          name="2"
          title="API/操作列表"
          v-if="formData.type === 2 && activeName === '2'"
        >
          <ms-edit-table
            :disabled="dialogType === 'view'"
            :column="column"
            :operateTree="true"
            :rowSaveBefore="rowSaveBefore"
            :table-list.sync="tableList"
            :dicData="dicData"
            @clickAfterIcon="clickAfterIcon"
          ></ms-edit-table>
        </el-collapse-item>
      </el-collapse>
    </div>

    <div class="md-component-btns">
      <el-button
        size="medium"
        type="primary"
        v-if="dialogType === 'view'"
        @click="
          () => {
            $emit('viewToEdit'), (dialogType = 'edit');
          }
        "
        >编辑
      </el-button>
      <el-button
        size="medium"
        v-if="activeName === '2' && dialogType !== 'view'"
        type="primary"
        @click="save"
        >保存
      </el-button>
      <el-button size="medium" v-if="activeName === '1'" @click="clickStep(1)"
        >下一步</el-button
      >
      <el-button size="medium" v-if="activeName === '2'" @click="clickStep(-1)"
        >上一步</el-button
      >
      <el-button size="medium" @click="$emit('removeThisTabs')">取消</el-button>
    </div>

    <add-properties
      ref="ap"
      @addToList="(v) => addToList(v, 'ap')"
      :disabled-attr="['dynamicFlag']"
      :default-value="{ dynamicFlag: formData.type === 1 ? 1 : 0 }"
    >
    </add-properties>
    <get-properties-dialog
      ref="gpd"
      :column="option.column"
      :type="formData.type"
      @addToList="(v) => addToList(v, 'gpd')"
    ></get-properties-dialog>
  </div>
</template>
<script>
import AddProperties from "@/views/DMDComponent/addProperties.vue";
import GetPropertiesDialog from "@/views/DMDComponent/getPropertiesDialog.vue";

import * as api from "@/api/modulManage/interface";
import MsEditTable from "@/components/ms-edit-table.vue";
import { request } from "axios";
import * as common from "@/api/common";

export default {
  name: "interfaceTemp",
  components: { MsEditTable, GetPropertiesDialog, AddProperties },
  provide() {
    return {
      allFormData: () => this.formData,
    };
  },
  data() {
    return {
      visible: false,
      activeName: 0,
      collapse: ["1", "2"],
      formData: {
        nameCn: "",
        name: "",
        type: "",
        refType: "",
        nameEn: "",
        describeCn: "",
        describeEn: "",
        configFlag: 0,
      },
      rules: {
        nameCn: [
          { required: true, message: "请输入中文名称", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入编码标识", trigger: "blur" }],
        type: [
          { required: true, message: "请选择接口类型", trigger: "change" },
        ],
        refType: [
          { required: true, message: "请选择接口数据类型", trigger: "change" },
        ],
        nameEn: [
          { required: true, message: "请输入英文名称", trigger: "blur" },
        ],
        describeCn: [
          { required: true, message: "请输入中文描述", trigger: "blur" },
        ],
      },

      propertiesData: [],
      loading: false,
      option: {
        height: "300px",
        calcHeight: 30,
        dialogWidth: 900,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: false,
        selection: true,
        labelWidth: 120,
        menuWidth: 200,
        viewBtn: false,
        dialogClickModal: false,
        tabs: true,
        delBtn: false,
        addBtn: false,
        editBtn: false,
        refreshBtn: false,
        columnBtn: false,
        align: "center",
        menu: false,
        column: [
          {
            label: "英文名称",
            prop: "columnName",
            overHidden: true,
            msSearch: true,
          },
          {
            label: "中文名称",
            prop: "nameCn",
            overHidden: true,
            msSearch: true,
          },
          {
            label: "中文描述",
            prop: "describeCn",
            overHidden: true,
          },
          {
            label: "英文描述",
            prop: "describeEn",
            overHidden: true,
          },
          {
            label: "类型",
            prop: "columnTypeName",
            overHidden: true,
          },
          {
            label: "分类",
            prop: "attributeTypeNameCn",
            overHidden: true,
          },
          {
            label: "必填",
            prop: "required",
            align: "center",
            dicData: [
              {
                label: "是",
                value: 1,
              },
              {
                label: "否",
                value: 0,
              },
            ],
          },

          {
            label: "单位组",
            prop: "unitGroup",
            type: "select",
            overHidden: true,
            dicUrl: "/api/manager-api/mx-dimension-group/list",
            props: {
              label: "nameCn",
              value: "oid",
            },
          },
          {
            label: "默认单位",
            prop: "unitName",
            overHidden: true,
          },
          {
            label: "默认值",
            prop: "columnDefault",
            overHidden: true,
            slot: true,
          },
        ],
      },
      propertiesSelection: [],

      column: [
        {
          label: "操作组名称",
          prop: "groupName",
          slot: true,
        },
        {
          label: "操作名称",
          prop: "name",
          cell: true,
        },
        {
          label: "API中文名称",
          prop: "apiNameCn",
          cell: true,
        },
        {
          label: "API英文名称",
          prop: "apiNameEn",
          cell: true,
        },
        {
          label: "API描述",
          prop: "apiDescribe",
          cell: true,
        },
      ],
      tableList: [],

      dialogType: "add",

      row: {},
      dicData: [],
    };
  },
  methods: {
    clickAfterIcon(name) {
      request({
        url: "/api/manager-api/mx-operation-group/deleteByName",
        method: "post",
        params: { name },
      }).then(() => {
        this.getGroupList();
      });
    },
    //行编辑后的保存
    rowSaveBefore(row) {
      let reg = /^[A-Za-z0-9_]{1,29}$/;
      let f = reg.test(row.name);
      if (!f && !row.name) {
        this.$message.warning("请输入正确的操作名称");
        return true;
      }
      return false;
    },
    // 从扩展属性列表中移除
    remove() {
      let data = this.deepCopy(this.propertiesSelection).map(
        (item) => item.oid
      );
      let properties = this.deepCopy(this.propertiesData);
      this.propertiesData = [];
      properties.forEach((item) => {
        if (!data.includes(item.oid)) {
          this.propertiesData.push(item);
        }
      });
    },

    //添加到扩展属性列表
    addToList(list, ref) {
      /*  let properties = this.deepCopy(this.propertiesData);
        this.propertiesData = [];
        if (properties.length > 0) {

          let ids = properties.map(item => item.oid ? item.oid : -1);
          list.forEach(item => {
            if (ids.length > 0 && item.oid && !ids.includes(item.oid)) {
              properties.push(item);
            }
          })
        } else {
          properties.push(...list);
        }
  */
      if (ref === "ap") {
        this.propertiesData.push(...list);
      } else {
        this.propertiesData = list;
      }

      this.$nextTick(() => {
        this.$refs[ref].close();
      });
    },

    // 保存
    save() {
      let method =
        this.dialogType === "add" ? "addInterface" : "updateInterface";
      let ids = this.propertiesData.map((item) => item.oid);
      let newArr = [...this.tableList];
      this.tableList.map((v) => {
        if (v.children && v.children.length > 0) {
          newArr = [...newArr, ...v.children];
        }
        return null;
      });
      api[method]({
        ...this.formData,
        extAttributeIds: ids,
        operations: newArr,
      }).then(() => {
        this.$message.success("保存成功");
        this.$emit("removeThisTabs");
        this.$emit("refresh");
      });
    },

    // 下一步/上一步
    async clickStep(v) {
      let flag = true;
      if (v > 0) flag = await this.$refs["form"].validate();
      if (flag) this.activeName = this.activeName - 0 + v + "";
    },

    resetDialog() {
      this.propertiesData = [];
      this.propertiesSelection = [];

      this.formData = {
        nameCn: "",
        name: "",
        type: "",
        refType: "",
        nameEn: "",
        describeCn: "",
        describeEn: "",
        configFlag: 0,
      };
    },

    getGroupList() {
      request({
        url: "/api/manager-api/mx-operation-group/list",
        method: "get",
      }).then((res) => {
        this.dicData = res.data.data;
      });
    },

    edit(row) {
      this.row = row;
      api.checkout({ id: row.oid }).then((res) => {
        this.visible = true;
        this.dialogType = "edit";
        this.resetDialog();
        this.activeName = "1";
        Object.assign(this.formData, res.data.data);
        this.propertiesData = this.formData.extAttributes;
        this.tableList = this.formData.operations;
        this.$emit("refresh");
      });
    },

    view(row) {
      this.row = row;
      api.getDetail({ oid: row.oid }).then((res) => {
        this.visible = true;
        this.dialogType = "view";
        this.resetDialog();
        this.activeName = "1";
        Object.assign(this.formData, res.data.data);
        this.propertiesData = this.formData.extAttributes;
        this.tableList = this.formData.operations;
      });
    },

    open() {
      this.resetDialog();
      this.visible = true;
      this.activeName = "1";
      this.dialogType = "add";
    },
    close() {
      this.visible = false;
    },
    getEnumList() {
      request({
        url: "/api/manager-api/mx-code-type/list",
        method: "get",
      }).then((res) => {
        this.enumList = res.data.data;
      });
    },
    setLabel({ associatedDataType, columnDefault, oid }, affix) {
      let obj = this.enumList.filter((i) => i.oid === associatedDataType)[0];
      if (obj && obj.name && columnDefault) {
        common.getDic(obj.name).then((res) => {
          let d = res.data.data.filter((i) => columnDefault == i.value);
          if (d && d.length > 0) {
            document.querySelector("#" + affix + oid).innerText = d[0].name;
          }
        });
      }
      return columnDefault;
    },
  },
  mounted() {
    this.getGroupList();
  },
  created() {
    this.getEnumList();
  },
};
</script>
